package com.lanchewuyou.user.driver.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.lanchewuyou.user.driver.R;
import com.lanchewuyou.user.driver.layouts.PhotoActivity;
import com.lanchewuyou.user.driver.lipeiui.CaseInfoActivity;
import com.lanchewuyou.user.driver.lipeiui.PickCarActivity;
import com.lanchewuyou.user.driver.modul.Config;
import com.lanchewuyou.user.driver.modul.OkHttpClientManager;
import com.squareup.okhttp.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

/**
 * 上传个人信息照片页
 */
public class UploadPersonPhoActivity extends AppCompatActivity implements View.OnClickListener {
    private Toolbar mToolbar;
    private ImageView shenfenzheng1, shenfenzheng2, jiashizheng1, jiashizheng2, xingshizheng1, xingshizheng2;
    private Button uploadShenfenzheng1, uploadShenfenzheng2, uploadJiashizheng1, uploadJiashizheng2, uploadXingshizheng1, uploadXingshizheng2;
    private Button chooseShenfenzheng1, chooseShenfenzheng2, chooseJiashizheng1, chooseJiashizheng2, chooseXingshizheng1, chooseXingshizheng2;
    private Button uploadPersonOver;
    private String imgurl1, imgurl2, imgurl3, imgurl4, imgurl5, imgurl6;
    private String orderId;
    private static String DRIVERID;
    private String saveName;
    private long time;
    private String FROMWHERE;
    private ProgressDialog progressUploadDialog;
    public static UploadPersonPhoActivity instance;

    private String PERSON_PHOTO_FOLDER = new File(Environment.getExternalStorageDirectory(), "").getPath() + "/lanchewuyou/person/";
    private Toast toast = null;

    private void showTextToast(String msg) {
        if (toast == null) {
            toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.show();
    }

    /*
    解析图片地址显示图片
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                try {
                    JSONObject json = (JSONObject) msg.obj;
                    String path1 = json.getJSONObject("1").getJSONArray("lists").getJSONObject(0).getString("img_path");
                    imgurl1 = path1;
                    onGilde(path1, shenfenzheng1);
                    Log.d("path", path1);
                    String path2 = json.getJSONObject("2").getJSONArray("lists").getJSONObject(0).getString("img_path");
                    imgurl2 = path2;
                    onGilde(path2, shenfenzheng2);
                    String path3 = json.getJSONObject("3").getJSONArray("lists").getJSONObject(0).getString("img_path");
                    imgurl3 = path3;
                    onGilde(path3, jiashizheng1);
                    String path4 = json.getJSONObject("4").getJSONArray("lists").getJSONObject(0).getString("img_path");
                    imgurl4 = path4;
                    onGilde(path4, jiashizheng2);
                    String path5 = json.getJSONObject("5").getJSONArray("lists").getJSONObject(0).getString("img_path");
                    imgurl5 = path5;
                    onGilde(path5, xingshizheng1);
                    String path6 = json.getJSONObject("6").getJSONArray("lists").getJSONObject(0).getString("img_path");
                    imgurl6 = path6;
                    onGilde(path6, xingshizheng2);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_person_pho);
        Intent intent = getIntent();
        FROMWHERE = intent.getStringExtra("from");
        instance = this;
        SharedPreferences sharedPreferences = getSharedPreferences(Config.PASSWORD_PATH, Activity.MODE_PRIVATE);
        DRIVERID = sharedPreferences.getString("driverid", "");
        if (FROMWHERE.equals("customdata")) {
            orderId = PickCarActivity.orderId;
        } else if (FROMWHERE.equals("caseinfo")) {
            orderId = CaseInfoActivity.orderId;
        }
        initViews();
        time = System.currentTimeMillis();//time时间戳
        saveName = time + orderId + DRIVERID;
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File file1 = new File(PERSON_PHOTO_FOLDER);
            if (!file1.exists()) {
                file1.mkdir();
            } else {
                Log.d("path", "exists");
            }
        } else {
            showTextToast("请确认已经插入SD卡");
        }
        OkHttpClientManager.getAsyn(Config.DRIVERORDERDETAIL + "&driverid=" + DRIVERID + "&orderid=" + orderId,
                new OkHttpClientManager.StringCallback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        showTextToast("加载失败");
                    }

                    @Override
                    public void onResponse(String response) {
                        Log.d("path", response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.getString("status");
                            if (status.equals("1")) {
                                JSONObject info = jsonObject.getJSONObject("info");
                                JSONObject json = info.getJSONObject("carimg").getJSONObject("lists");
                                Message message = new Message();
                                message.obj = json;
                                message.what = 1;
                                handler.sendMessage(message);
                            } else {
                                showTextToast("没有获取到详情");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void initViews() {
        mToolbar = (Toolbar) findViewById(R.id.upload_photo_toolbar);
        mToolbar.setTitle("上传照片");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        shenfenzheng1 = (ImageView) findViewById(R.id.upload_shenfenzheng1);
        shenfenzheng1.setOnClickListener(this);
        shenfenzheng2 = (ImageView) findViewById(R.id.upload_shenfenzheng2);
        shenfenzheng2.setOnClickListener(this);
        jiashizheng1 = (ImageView) findViewById(R.id.upload_jiashizheng1);
        jiashizheng1.setOnClickListener(this);
        xingshizheng1 = (ImageView) findViewById(R.id.upload_xingshizheng1);
        xingshizheng1.setOnClickListener(this);
        jiashizheng2 = (ImageView) findViewById(R.id.upload_jiashizheng2);
        jiashizheng2.setOnClickListener(this);
        xingshizheng2 = (ImageView) findViewById(R.id.upload_xingshizheng2);
        xingshizheng2.setOnClickListener(this);
        uploadShenfenzheng1 = (Button) findViewById(R.id.upload_shenfenzheng1_btn);
        uploadShenfenzheng1.setOnClickListener(this);
        uploadShenfenzheng2 = (Button) findViewById(R.id.upload_shenfenzheng2_btn);
        uploadShenfenzheng2.setOnClickListener(this);
        uploadJiashizheng1 = (Button) findViewById(R.id.upload_jiashizheng1_btn);
        uploadJiashizheng1.setOnClickListener(this);
        uploadXingshizheng1 = (Button) findViewById(R.id.upload_xingshizheng1_btn);
        uploadXingshizheng1.setOnClickListener(this);
        chooseShenfenzheng1 = (Button) findViewById(R.id.choose_shenfenzheng1_btn);
        chooseShenfenzheng1.setOnClickListener(this);
        chooseShenfenzheng2 = (Button) findViewById(R.id.choose_shenfenzheng2_btn);
        chooseShenfenzheng2.setOnClickListener(this);
        chooseJiashizheng1 = (Button) findViewById(R.id.choose_jiashizheng1_btn);
        chooseJiashizheng1.setOnClickListener(this);
        chooseXingshizheng1 = (Button) findViewById(R.id.choose_xingshizheng1_btn);
        chooseXingshizheng1.setOnClickListener(this);
        chooseJiashizheng2 = (Button) findViewById(R.id.choose_jiashizheng2_btn);
        chooseJiashizheng2.setOnClickListener(this);
        chooseXingshizheng2 = (Button) findViewById(R.id.choose_xingshizheng2_btn);
        chooseXingshizheng2.setOnClickListener(this);
        uploadJiashizheng2 = (Button) findViewById(R.id.upload_jiashizheng2_btn);
        uploadJiashizheng2.setOnClickListener(this);
        uploadXingshizheng2 = (Button) findViewById(R.id.upload_xingshizheng2_btn);
        uploadXingshizheng2.setOnClickListener(this);
        uploadPersonOver = (Button) findViewById(R.id.upload_person_photo_over);
        uploadPersonOver.setOnClickListener(this);
        progressUploadDialog = new ProgressDialog(this);
        progressUploadDialog.setTitle("上传图片中");
        progressUploadDialog.setMessage("请稍等");
        progressUploadDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressUploadDialog.setCancelable(true);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.upload_person_photo_over:
                if (FROMWHERE.equals("customdata")) {
                    Intent intent = new Intent(UploadPersonPhoActivity.this, CarPhotoActivity.class);
                    intent.putExtra("from", "personpho");
                    startActivity(intent);
                    finish();
                } else if (FROMWHERE.equals("caseinfo")) {
                    finish();
                }
                break;
            case R.id.upload_shenfenzheng1:
                Intent i1 = new Intent(UploadPersonPhoActivity.this, PhotoActivity.class);
                i1.putExtra("url", imgurl1);
                startActivity(i1);
                break;
            case R.id.upload_shenfenzheng2:
                Intent i2 = new Intent(UploadPersonPhoActivity.this, PhotoActivity.class);
                i2.putExtra("url", imgurl2);
                startActivity(i2);
                break;
            case R.id.upload_jiashizheng1:
                Intent i3 = new Intent(UploadPersonPhoActivity.this, PhotoActivity.class);
                i3.putExtra("url", imgurl3);
                startActivity(i3);
                break;
            case R.id.upload_jiashizheng2:
                Intent i4 = new Intent(UploadPersonPhoActivity.this, PhotoActivity.class);
                i4.putExtra("url", imgurl4);
                startActivity(i4);
                break;
            case R.id.upload_xingshizheng1:
                Intent i5 = new Intent(UploadPersonPhoActivity.this, PhotoActivity.class);
                i5.putExtra("url", imgurl5);
                startActivity(i5);
                break;
            case R.id.upload_xingshizheng2:
                Intent i6 = new Intent(UploadPersonPhoActivity.this, PhotoActivity.class);
                i6.putExtra("url", imgurl6);
                startActivity(i6);
                break;
            case R.id.upload_shenfenzheng1_btn:
                uploadPhoto(1);
                break;
            case R.id.upload_shenfenzheng2_btn:
                uploadPhoto(2);
                break;
            case R.id.upload_jiashizheng1_btn:
                uploadPhoto(3);
                break;
            case R.id.upload_jiashizheng2_btn:
                uploadPhoto(4);
                break;
            case R.id.upload_xingshizheng1_btn:
                uploadPhoto(5);
                break;
            case R.id.upload_xingshizheng2_btn:
                uploadPhoto(6);
                break;
            case R.id.choose_shenfenzheng1_btn:
                startPhoActivity(1);
                break;
            case R.id.choose_shenfenzheng2_btn:
                startPhoActivity(2);
                break;
            case R.id.choose_jiashizheng1_btn:
                startPhoActivity(3);
                break;
            case R.id.choose_jiashizheng2_btn:
                startPhoActivity(4);
                break;
            case R.id.choose_xingshizheng1_btn:
                startPhoActivity(5);
                break;
            case R.id.choose_xingshizheng2_btn:
                startPhoActivity(6);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        String path1 = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS).get(0);
                        onGilde(path1, shenfenzheng1);
                        imgurl1 = path1;
                        Bitmap bitmap = getBitmapFromFile(path1);
                        bitmap = resizeBitmap(bitmap, 600);
                        saveBitmap(bitmap, saveName + "1");
                    }
                }
                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        String path2 = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS).get(0);
                        onGilde(path2, shenfenzheng2);
                        imgurl2 = path2;
                        Bitmap bitmap = getBitmapFromFile(path2);
                        bitmap = resizeBitmap(bitmap, 600);
                        saveBitmap(bitmap, saveName + "2");
                    }
                }
                break;
            case 3:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        String path3 = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS).get(0);
                        onGilde(path3, jiashizheng1);
                        imgurl3 = path3;
                        Bitmap bitmap = getBitmapFromFile(path3);
                        bitmap = resizeBitmap(bitmap, 600);
                        saveBitmap(bitmap, saveName + "3");
                    }
                }
                break;
            case 4:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        String path4 = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS).get(0);
                        onGilde(path4, jiashizheng2);
                        imgurl4 = path4;
                        Bitmap bitmap = getBitmapFromFile(path4);
                        bitmap = resizeBitmap(bitmap, 600);
                        saveBitmap(bitmap, saveName + "4");
                    }
                }
                break;
            case 5:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        String path5 = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS).get(0);
                        onGilde(path5, xingshizheng1);
                        imgurl5 = path5;
                        Bitmap bitmap = getBitmapFromFile(path5);
                        bitmap = resizeBitmap(bitmap, 600);
                        saveBitmap(bitmap, saveName + "5");
                    }
                }
                break;
            case 6:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        String path6 = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS).get(0);
                        onGilde(path6, xingshizheng2);
                        imgurl6 = path6;
                        Bitmap bitmap = getBitmapFromFile(path6);
                        bitmap = resizeBitmap(bitmap, 600);
                        saveBitmap(bitmap, saveName + "6");
                    }
                }
                break;
        }

    }

    private void onGilde(String path, ImageView imageView) {
        Glide.with(UploadPersonPhoActivity.this)
                .load(path)
                .centerCrop()
                .thumbnail(0.1f)
                .placeholder(me.iwf.photopicker.R.drawable.ic_photo_black_48dp)
                .error(me.iwf.photopicker.R.drawable.ic_broken_image_black_48dp)
                .into(imageView);
    }

    /**
     * 保存图片到具体位置
     *
     * @param bitmap
     */
    public void saveBitmap(Bitmap bitmap, String saveName) {
        File f = new File(PERSON_PHOTO_FOLDER, saveName + ".jpg");
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 固定宽度压缩图片
     *
     * @param bitmap
     * @param newWidth
     * @return
     */
    public static Bitmap resizeBitmap(Bitmap bitmap, int newWidth) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float temp = ((float) height) / ((float) width);
        int newHeight = (int) ((newWidth) * temp);
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        // resize the bit map
        matrix.postScale(scaleWidth, scaleHeight);
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        //bitmap.recycle();
        return resizedBitmap;
    }

    /**
     * 从存储路径获取bitmap
     *
     * @param filePath
     * @return
     */
    public static Bitmap getBitmapFromFile(String filePath) {
        Bitmap bitmap = BitmapFactory.decodeFile(filePath);
        return bitmap;
    }


    /**
     * 上传照片方法
     *
     * @param photoid
     */
    private void uploadPhoto(int photoid) {
        progressUploadDialog.show();
        File f = new File(PERSON_PHOTO_FOLDER, time + orderId + DRIVERID + photoid + ".jpg");
        if (f.exists()) {
            try {
                OkHttpClientManager.postAsyn(Config.UPLOADIMG + orderId + "&driverid=" + DRIVERID + "&type=" + photoid, new OkHttpClientManager.StringCallback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        Log.d("jpg", "error");
                        progressUploadDialog.dismiss();
                        showTextToast("上传失败");
                    }

                    @Override
                    public void onResponse(String response) {
                        Log.d("jpg", response);
                        progressUploadDialog.dismiss();
                        showTextToast("上传成功");
                    }
                }, f, "imageinfo");
            } catch (IOException e) {
                e.printStackTrace();
                progressUploadDialog.dismiss();
                showTextToast("上传失败");
            }
        } else {
            Log.d("jpg", "null");
            progressUploadDialog.dismiss();
            showTextToast("照片不存在");
        }
    }

    /**
     * 选择图片页面
     * @param photoid
     */
    private void startPhoActivity(int photoid) {
        PhotoPickerIntent intent1 = new PhotoPickerIntent(UploadPersonPhoActivity.this);
        intent1.setPhotoCount(1);
        intent1.setShowCamera(true);
        startActivityForResult(intent1, photoid);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_upload_person_pho, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            if (FROMWHERE.equals("customdata")) {
                showBackDialog();
            } else if (FROMWHERE.equals("caseinfo")) {
                finish();
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showBackDialog() {
        new MaterialDialog.Builder(this)
                .title("退出任务")
                .content("点击确定将退出您正在执行的任务。")
                .positiveText("确定")
                .negativeText("取消")
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        finish();
                    }

                    @Override
                    public void onNegative(MaterialDialog dialog) {
                        super.onNegative(dialog);
                    }
                })
                .show();
    }

    @Override
    public void onBackPressed() {
        if (FROMWHERE.equals("customdata")) {
            showBackDialog();
        } else if (FROMWHERE.equals("caseinfo")) {
            finish();
        }
    }
}
